﻿using System;
using System.Collections.Generic;

using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;

using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Runtime.Serialization;

namespace AllMyMoney.WCFService
{
    // 
    // Data contract for International SOAP header element 
    // 
    [DataContract(Name = "International", Namespace = "http://www.w3.org/2005/09/ws-i18n")]
    public sealed class International
    {
        public International()
        {
        }

        [DataMember(Name = "Locale")]
        public string Locale
        {
            get { return _locale; }
            set { _locale = value; }
        }

        [DataMember(Name = "TZ")]
        public string Tz
        {
            get { return _tz; }
            set { _tz = value; }
        }

        [DataMember(Name = "Preferences")]
        public List<Preferences> Preferences
        {
            get { return _preferences; }
            set { _preferences = value; }
        }

        public static International GetHeaderFromIncomeMessage()
        {
            MessageHeaders headers = OperationContext.Current.IncomingMessageHeaders;

            foreach (MessageHeaderInfo header in headers.UnderstoodHeaders)
            {
                if (header.Name == "International" && header.Namespace == "http://www.w3.org/2005/09/ws-i18n")
                {
                    International internationalHeader = headers.GetHeader<International>(header.Name, header.Namespace);
                    return internationalHeader;
                }
            }

            return null;
        }

        private string _locale;
        private string _tz;
        private List<Preferences> _preferences;
    }

    //
    // Custom field type for International SOAP header (see above)
    //
    public class Preferences : IXmlSerializable
    {
        public XmlNode AnyElement
        {
            get { return _anyElement; }
            set { _anyElement = value; }
        }

        public XmlSchema GetSchema()
        {
            return null;
        }

        public void ReadXml(XmlReader reader)
        {
            XmlDocument document = new XmlDocument();
            _anyElement = document.ReadNode(reader);
        }

        public void WriteXml(XmlWriter writer)
        {
            _anyElement.WriteTo(writer);
        }

        private XmlNode _anyElement;
    }
}
